package com.module.ble.db

import androidx.sqlite.db.SimpleSQLiteQuery
import androidx.sqlite.db.SupportSQLiteQuery

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/09/25
 *
 * 描述：压力查询辅助类
 *
 * 修订历史：
 *
 */
object UseStressTableQueryHelper {
    /**
     * 根据时间戳数组查询user_stress表中每天的数据
     * @param dayStartTimestamps 每天0点0分0秒的时间戳数组（通过TimeUtils.getDayStartTimestamps获取）
     * @return SupportSQLiteQuery
     */
    fun createDayStartTimestampsQuery(dayStartTimestamps: Array<Long>): SupportSQLiteQuery {
        if (dayStartTimestamps.isEmpty()) {
            throw IllegalArgumentException("Day start timestamps array cannot be empty")
        }

        // 将每个时间戳转换为当天的时间范围（0点到23:59:59.999）
        val timeRanges = dayStartTimestamps.map { dayStart ->
            val dayEnd = dayStart + 24 * 60 * 60 * 1000 - 1 // 当天23:59:59.999
            Pair(dayStart, dayEnd)
        }

        // 构建多个时间段的OR条件SQL语句
        val conditions = timeRanges.joinToString(" OR ") { timeRange ->
            "(createdTime >= ${timeRange.first} AND createdTime <= ${timeRange.second})"
        }

        val sql = "SELECT * FROM user_stress WHERE $conditions ORDER BY createdTime ASC"
        return SimpleSQLiteQuery(sql)
    }

    /**
     * 根据时间戳数组查询user_stress表中每天的最新数据
     * @param dayStartTimestamps 每天0点0分0秒的时间戳数组（通过TimeUtils.getDayStartTimestamps获取）
     * @return SupportSQLiteQuery
     */
    fun createDayStartTimestampsLatestQuery(dayStartTimestamps: Array<Long>): SupportSQLiteQuery {
        if (dayStartTimestamps.isEmpty()) {
            throw IllegalArgumentException("Day start timestamps array cannot be empty")
        }

        // 为每天构建子查询，获取当天最新的一条记录
        val subQueries = dayStartTimestamps.map { dayStart ->
            val dayEnd = dayStart + 24 * 60 * 60 * 1000 - 1
            "(SELECT * FROM user_stress WHERE createdTime >= $dayStart AND createdTime <= $dayEnd ORDER BY createdTime DESC LIMIT 1)"
        }

        val sql = subQueries.joinToString(" UNION ALL ") + " ORDER BY createdTime ASC"
        return SimpleSQLiteQuery(sql)
    }
}